package com.smartwebee.android.blespp.hospital.fragment;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.smartwebee.android.blespp.R;
import com.smartwebee.android.blespp.bean.ItemBean;
import com.smartwebee.android.blespp.databinding.FragmentExerciseBinding;
import com.smartwebee.android.blespp.eventbusclass.AddPlanEvent;
import com.smartwebee.android.blespp.hospital.adapter.ItemAdapter;
import com.smartwebee.android.blespp.hospital.adapter.PlanExpandableAdapter;
import com.smartwebee.android.blespp.http.HttpCallback;
import com.smartwebee.android.blespp.http.HttpRequest;
import com.smartwebee.android.blespp.http.RequestInterface;
import com.smartwebee.android.blespp.http.VolleyReqQueue;
import com.smartwebee.android.blespp.resp.BaseResp;
import com.smartwebee.android.blespp.resp.GetPlanResp;
import com.smartwebee.android.blespp.utils.UIUtils;
import com.smartwebee.android.blespp.utils.Utils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExerciseFragment extends BaseFragment implements RequestInterface {
    private FragmentExerciseBinding binding;
    private PlanExpandableAdapter expandableAdapter;
    private AddPlanEvent event;

    public ExerciseFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_exercise, container, false);
        TAG = "ExerciseFragment";
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        List<ItemBean> list = new ArrayList<>();
//        list.add(new ItemBean(Utils.MODE_1, "1", R.drawable.item1, getResources().getString(R.string.item1)));
        list.add(new ItemBean(Utils.MODE_2, "2", R.drawable.item2, getResources().getString(R.string.item2)));
        list.add(new ItemBean(Utils.MODE_3, "3", R.drawable.item3, getResources().getString(R.string.item3)));
        list.add(new ItemBean(Utils.MODE_4, "4", R.drawable.item4, getResources().getString(R.string.item4)));
        list.add(new ItemBean(Utils.MODE_5, "5", R.drawable.item5, getResources().getString(R.string.item5)));
        list.add(new ItemBean(Utils.MODE_6, "6", R.drawable.item6, getResources().getString(R.string.item6)));
        list.add(new ItemBean(Utils.MODE_7, "7", R.drawable.item7, getResources().getString(R.string.item7)));
//        list.add(new ItemBean(Utils.MODE_8, "8", R.drawable.item8, getResources().getString(R.string.item8)));
        list.add(new ItemBean(Utils.MODE_9, "9", R.drawable.item9, getResources().getString(R.string.item9)));
        list.add(new ItemBean(Utils.MODE_10, "10", R.drawable.item10, getResources().getString(R.string.item10)));
        list.add(new ItemBean(Utils.MODE_11, "11", R.drawable.item11, getResources().getString(R.string.item11)));
        list.add(new ItemBean(Utils.MODE_12, "12", R.drawable.item12, getResources().getString(R.string.item12)));
        ItemAdapter adapter = new ItemAdapter(getActivity(), list);
        binding.listviewItem.setAdapter(adapter);

        expandableAdapter = new PlanExpandableAdapter(getActivity());
        binding.listviewPlan.setAdapter(expandableAdapter);
        binding.btnClearPlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                httpDeletePlan();
            }
        });
        expand();
        binding.listviewPlan.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        initData();

    }

    private void initData() {
        requestQueue = VolleyReqQueue.getInstance(getActivity()).getRequestQueue();
        httpGetPlan();
    }

    /**
     *
     * @param jid 计划编号
     * @param pid 项目编号
     */
    private void httpUploadPlan(final String jid, final String pid) {
        showLoading();
        HttpRequest httpRequest = new HttpRequest(Request.Method.POST, Utils.uploadPlan,
                this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("sn", Utils.registerResp.getData().getSn());
                map.put("jid", jid);
                map.put("pid", pid);
                return map;
            }
        };
        requestQueue.add(httpRequest);
    }

    private void httpGetPlan() {
        showLoading();
        HttpRequest httpRequest = new HttpRequest(Request.Method.POST, Utils.getPlan,
                this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("sn", Utils.registerResp.getData().getSn());
                return map;
            }
        };
        requestQueue.add(httpRequest);
    }

    private void httpDeletePlan() {
        showLoading();
        HttpRequest httpRequest = new HttpRequest(Request.Method.POST, Utils.deletePlan,
                this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("sn", Utils.registerResp.getData().getSn());
                return map;
            }
        };
        requestQueue.add(httpRequest);
    }

    private void expand() {
        for (int i = 0; i < expandableAdapter.getGroupCount(); i++) {
            binding.listviewPlan.expandGroup(i);
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddPlanEvent event) {
        this.event = event;

        if (!expandableAdapter.getChildItem().get(event.getPosition()).contains(event.getBean().getTitle())) {
            httpUploadPlan(String.valueOf(event.getPosition() + 1), Utils.getModeId(event.getBean().getTitle()));
        } else {
            UIUtils.showTips(getActivity(), "该项目已存在，不能重复添加");
        }


    }

    private void deletePlan() {
        expandableAdapter.clearItems();
        Utils.childItem = expandableAdapter.getChildItem();
    }

    @Override
    public void onSuccess(String id, String resp) {
        dismissLoading();
        switch (id) {
            case Utils.deletePlan:
                BaseResp deletePlan = new Gson().fromJson(resp, BaseResp.class);
                if (Utils.parseData(deletePlan)) {
                    deletePlan();
                } else {
                    UIUtils.showTips(getActivity(), deletePlan.getMsg());
                }
                break;
            case Utils.getPlan:
                GetPlanResp getPlanResp = new Gson().fromJson(resp, GetPlanResp.class);
                if (Utils.parseData(getPlanResp)) {
                    deletePlan();
                    for (int i = 0; i < getPlanResp.getData().size(); i ++) {
                        String[] pids = getPlanResp.getData().get(i).getPid().split(",");
                        for (int j = 0; j < pids.length; j ++) {
                            expandableAdapter.addChildItem(Integer.valueOf(getPlanResp.getData().get(i).getJid()) - 1,
                                    Utils.getModeNameById(pids[j]));
                            expand();
                            Utils.childItem = expandableAdapter.getChildItem();
                        }
                    }
                } else {
                    UIUtils.showTips(getActivity(), getPlanResp.getMsg());
                }
                break;
            case Utils.uploadPlan:
                BaseResp upload = new Gson().fromJson(resp, BaseResp.class);
                if (Utils.parseData(upload)) {
                    httpGetPlan();
                } else {
                    UIUtils.showTips(getActivity(), upload.getMsg());
                }

                break;
        }
    }

    @Override
    public void onError(String error) {
        dismissLoading();
        UIUtils.showTips(getActivity(), error);
    }
}
